package com.web.tag;

import java.io.UnsupportedEncodingException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class TextTag extends TagSupport {

	private String text;
	private String len;
	private String suffix;

	@SuppressWarnings("static-access")
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			if (len != null) {
				if (suffix == null)
					suffix = "";
				int length = Integer.parseInt(len);
				text = text == null ? "" : text.trim();
				text = this.bSubstring(text, length, suffix);
			}
			out.print(text);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	private static String bSubstring(String s, int length, String suffix) throws UnsupportedEncodingException {
		if (s == null)
			return "";
		byte[] bytes = s.getBytes("Unicode");
		boolean state = false;
		if (bytes.length > length)
			state = true;
		else
			return s;
		int n = 0; // 表示当前的字节数
		int i = 2; // 要截取的字节数，从第3个字节开始
		for (; i < bytes.length && n < length; i++) {
			// 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
			if (i % 2 == 1) {
				n++; // 在UCS2第二个字节时n加1
			} else {
				// 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
				if (bytes[i] != 0) {
					n++;
				}
			}
		}
		// 如果i为奇数时，处理成偶数
		if (i % 2 == 1) {
			// 该UCS2字符是汉字时，去掉这个截一半的汉字
			if (bytes[i - 1] != 0)
				i = i - 1;
			// 该UCS2字符是字母或数字，则保留该字符
			else
				i = i + 1;
		}
		String text = new String(bytes, 0, i, "Unicode");
		if (state)
			text += suffix;
		return text;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getLen() {
		return len;
	}

	public void setLen(String len) {
		this.len = len;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

}
